
# 安装python环境
# 安装playwright: pip install playwright
# 及浏览器: playwright install

from playwright.async_api import async_playwright
import asyncio

async def get_info(browser,li,semaphore):
    async with semaphore:
        page_info = await browser.new_page()
        await page_info.goto(f'https:{li["href"]}')
        await page_info.mouse.wheel(0, 100000)
        await asyncio.sleep(3)
        percent = await (await page_info.query_selector_all('xpath=//*[@id="comment"]/div[2]/div[1]/div[1]/div'))[0].inner_text()
        await page_info.close()
        return {**li,'percent':percent}



async def get_list(browser,search_str):
    page = await browser.new_page()
    await page.goto(f'https://search.jd.com/Search?keyword={search_str}')
    li_list = await page.query_selector_all('xpath=//*[@id="J_goodsList"]/ul/li')
    
    async def parse_li(li):
        title =  await (await li.query_selector_all('xpath=//em'))[1].inner_text()
        price = await (await li.query_selector_all('xpath=//i'))[0].inner_text()
        href = await (await li.query_selector_all('xpath=//a'))[0].get_attribute('href')
        
        obj={
            'title':title,
            'price':price,
            'href':href,
        } 
        return obj 
    li_obj_list=list(map(parse_li,li_list))
    await page.close()
    return li_obj_list
    

async def main(search_str):
    async with async_playwright() as p:
        browser_type = p.chromium
        browser = await browser_type.launch(headless=False)
        # browser = browser_type.launch(headless=True)
        lis = await get_list(browser,search_str)
        lis = lis[:4]
        
        semaphore = asyncio.Semaphore(2)
        tasks = [get_info(browser,lis[i],semaphore) for i in range(len(lis))]
        res_lis = await asyncio.gather(*tasks)
        print(res_lis)
    
if __name__ == '__main__':
    asyncio.run(main('手机'))
    